﻿using AutoMapper;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Read.Apilication.Common.MenuRole;
using B.S.BasicData.Read.DTOS;
using MediatR;

namespace B.S.BasicData.Read.Apilication.Handler.MenuRole
{
    public class GetMenuCommandHandle:IRequestHandler<GetMenuCommand, ApiResult<List<MenuRoleDto>>>
    {
        private readonly IBaseRepository<MenuModel> MenuDal;
        private readonly IMapper mapper;

        public GetMenuCommandHandle(IBaseRepository<MenuModel> menuDal, IMapper mapper)
        {
            MenuDal = menuDal;
            this.mapper = mapper;
        }



        public Task<ApiResult<List<MenuRoleDto>>> Handle(GetMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<MenuRoleDto>> result = new ApiResult<List<MenuRoleDto>>();

            result.Code = ApiEnum.Success;
            result.Message = "菜单树形结构显示成功";
            result.Data = gettree(0);
            return Task.FromResult(result);
        }

        private List<MenuRoleDto> gettree(int parment)
        {
            var info = MenuDal.GetAll().Where(x => x.ParentId == parment).ToList();
            var model = mapper.Map<List<MenuRoleDto>>(info);
            foreach (var item in model)
            {
                item.Childer = gettree(item.MenuId);
            }
            return model;
        }


    }
}
